package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.ParkingDTO;
import com.property.demo.model.Parking;
import com.property.demo.service.ParkingService;
import com.property.demo.util.SortUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/api/parkings")
public class ParkingController {

    @Autowired
    private ParkingService parkingService;

    @GetMapping
    public ResponseEntity<?> getAllParkings(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "id,desc") String[] sort) {
        
        try {
            List<Sort.Order> orders = SortUtil.getOrders(sort);
            Pageable pageable = PageRequest.of(page, size, Sort.by(orders));
            
            Page<Parking> parkingsPage;
            if (communityId != null || (name != null && !name.isEmpty()) || (status != null && !status.isEmpty())) {
                parkingsPage = parkingService.findByFilters(communityId, name, status, pageable);
            } else {
                parkingsPage = parkingService.findAll(pageable);
            }
            
            List<ParkingDTO> parkingDTOs = parkingsPage.getContent().stream()
                    .map(ParkingDTO::new)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", parkingDTOs);
            response.put("currentPage", parkingsPage.getNumber());
            response.put("totalItems", parkingsPage.getTotalElements());
            response.put("totalPages", parkingsPage.getTotalPages());
            
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(
                new ApiResponse(false, "获取车位列表失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    @GetMapping("/all")
    public ResponseEntity<List<ParkingDTO>> getAllParkingsNoPage() {
        List<Parking> parkings = parkingService.findAll();
        List<ParkingDTO> parkingDTOs = parkings.stream()
                .map(ParkingDTO::new)
                .collect(Collectors.toList());
        return new ResponseEntity<>(parkingDTOs, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<ParkingDTO> getParkingById(@PathVariable Long id) {
        Parking parking = parkingService.findById(id);
        ParkingDTO parkingDTO = new ParkingDTO(parking);
        return new ResponseEntity<>(parkingDTO, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<ApiResponse> createParking(@RequestBody Parking parking) {
        Parking savedParking = parkingService.save(parking);
        ParkingDTO parkingDTO = new ParkingDTO(savedParking);
        return new ResponseEntity<>(
                new ApiResponse(true, "Parking created successfully", parkingDTO),
                HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse> updateParking(
            @PathVariable Long id, @RequestBody Parking parkingDetails) {
        Parking updatedParking = parkingService.update(id, parkingDetails);
        ParkingDTO parkingDTO = new ParkingDTO(updatedParking);
        return new ResponseEntity<>(
                new ApiResponse(true, "Parking updated successfully", parkingDTO),
                HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse> deleteParking(@PathVariable Long id) {
        parkingService.delete(id);
        return new ResponseEntity<>(
                new ApiResponse(true, "Parking deleted successfully"),
                HttpStatus.OK);
    }

    @GetMapping("/community/{communityId}")
    public ResponseEntity<List<ParkingDTO>> getParkingsByCommunityId(@PathVariable Long communityId) {
        List<Parking> parkings = parkingService.findByCommunityId(communityId);
        List<ParkingDTO> parkingDTOs = parkings.stream()
                .map(ParkingDTO::new)
                .collect(Collectors.toList());
        return new ResponseEntity<>(parkingDTOs, HttpStatus.OK);
    }

    @GetMapping("/search")
    public ResponseEntity<List<ParkingDTO>> searchParkings(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) String status) {
        
        List<Parking> parkings;
        
        if (name != null && communityId != null) {
            parkings = parkingService.findByNameContainingAndCommunityId(name, communityId);
        } else if (communityId != null) {
            parkings = parkingService.findByCommunityId(communityId);
        } else if (name != null) {
            parkings = parkingService.findByNameContaining(name);
        } else if (status != null) {
            parkings = parkingService.findByStatus(status);
        } else {
            parkings = parkingService.findAll();
        }
        
        List<ParkingDTO> parkingDTOs = parkings.stream()
                .map(ParkingDTO::new)
                .collect(Collectors.toList());
        return new ResponseEntity<>(parkingDTOs, HttpStatus.OK);
    }
} 